class PostMsg {
    stacks = {};
    win;
    constructor(win) {
        this.win = win;
        this.isSelf = (win === window);
        window.onmessage = (e) => {
            const res = e.data;
            if (res && res.type) {
                if (this.stacks[res.type]) {
                    this.stacks[res.type](res.data);
                }
            }
        };
    }

    on(name, callback) {
        if (this.isSelf) {
            callback();
        } else {
            this.stacks[name] = callback;
        }
    }

    send(type, data) {
        if (this.win) {
            this.win.postMessage({
                type,
                data
            }, '*');
        }
    }

    request(type, data, cb) {
        if (cb) {
            this.stacks[type] = cb;
        }
        this.send(type, data);
    }

    async req(type, data) {
        const self = this;
        return new Promise((resolve, reject) => {
            self.request(type, data, (res) => {
                resolve(res);
            });
        });
    }
}